﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json.Linq;
using Qimen.Api;
using Qimen.Api.Request;
using Qimen.Api.Response;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;
using System.Xml;
using Newtonsoft.Json;
using QimenCloud.Api;

namespace Taobao.Open.Platform
{
    public class GetOrderSensitiveInfo : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var request = dataset.GetJsonObject("request");
            var constant = dataset.GetJsonObject("constant");           
            var taobaoQimenAPIConfig = constant.GetNecessaryJsonObject("taobaoQimenAPIConfig", "constant");
            //var eComOrderSensitiveConfig = constant.GetNecessaryJsonObject("eComOrderSensitiveConfig", "constant");

            string eShopCode = request.GetJsonObjectStringValue("eShopCode");
            string orderId = request.GetJsonObjectStringValue("orderId");
            //从参数取值，因为request是透传，有些请求不带以下参数
            JObject argsParams = null;
            if (args != null && args.Length > 0)
            {
                argsParams = args[0] as JObject;
            }
            if (argsParams != null
                && !string.IsNullOrWhiteSpace(argsParams.GetJsonObjectStringValue("eShopCode"))
                && !string.IsNullOrWhiteSpace(argsParams.GetJsonObjectStringValue("orderId"))
                )
            {
                eShopCode = argsParams.GetJsonObjectStringValue("eShopCode");
                orderId = argsParams.GetJsonObjectStringValue("orderId");
            }

            if (string.IsNullOrWhiteSpace(eShopCode) || string.IsNullOrWhiteSpace(orderId))
                throw new Exception("eShopCode or orderId is empty");

            if (orderId.Contains("-"))
            {
            var orderIds = orderId.Split('-');
            if (orderIds.Length == 2)
                orderId = orderIds[0];
            }
            if (orderId.Contains("X"))
            {
                var orderIds = orderId.Split('X');
                if (orderIds.Length == 2)
                    orderId = orderIds[0];
            }

            //string parentPath = string.Format("constant.eComOrderSensitiveConfig.{0}", eShopCode);
            //var config = eComOrderSensitiveConfig.GetJsonObject(eShopCode);

            //if (config == null)
            //{
            //    var eplatform = dataset.GetJsonObjectValue("eplatform");
            //    if (eplatform != null && eplatform.Type == JTokenType.Array && eplatform.HasValues && eplatform.First.Type == JTokenType.Object)
            //    {
            //        string ePlatformCode = (eplatform.First as JObject).GetJsonObjectStringValue("ePlatformCode");
            //        config = eComOrderSensitiveConfig.GetJsonObject(ePlatformCode);
            //    }
            //}

            //if (config == null)
            //    throw new ConfigException("{0} is null or not an object", parentPath);

            string url = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("url", "constant.taobaoQimenAPIConfig");
            string appkey = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("app_key", "constant.taobaoQimenAPIConfig");
            string appsecret = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("app_secret", "constant.taobaoQimenAPIConfig");
           
            try
            {
                //var proxyHttpClientHandler = new HttpClientHandler();

                //if (proxy != null && proxy.Type == JTokenType.String && !string.IsNullOrWhiteSpace(proxy.ToString()) && proxy.ToString().IndexOf(":") > -1)
                //{
                //    string[] hostAndPort = proxy.ToString().Split(':');
                //    int port = 0;
                //    if (int.TryParse(hostAndPort[1], out port))
                //    {
                //        proxyHttpClientHandler.Proxy = new WebProxy(hostAndPort[0], port);
                //        proxyHttpClientHandler.UseProxy = true;
                //    }
                //}
                //else if (proxy != null && proxy.Type == JTokenType.Boolean && !proxy.Value<bool>())
                //{
                //    proxyHttpClientHandler.Proxy = null;
                //    proxyHttpClientHandler.UseProxy = false;
                //}

                if (url.ToLower().Contains("qimen"))
                {
                    string customerId = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("customerid", "constant.taobaoQimenAPIConfig");
                    var proxy = taobaoQimenAPIConfig.GetJsonObjectValue("proxy");
                    //通过SDK调用奇门接口
                    bool useProxy = proxy == null || proxy.Type != JTokenType.Boolean ? true : proxy.Value<bool>();
                    IQimenClient client = new MyQimenClient(url, appkey, appsecret, useProxy);
                    ReceiverinfoQueryRequest req = new ReceiverinfoQueryRequest();
                    req.CustomerId = customerId;
                    req.Version = "2.0";
                    req.OwnerCode = eShopCode;
                    req.DeliveryOrderCode = orderId;
                    ReceiverinfoQueryResponse rsp = client.Execute(req);

                    string responseXML = rsp.Body;

                    XmlDocument doc = new XmlDocument();
                    //2.加载 xml 文档
                    doc.LoadXml(responseXML);
                    //3.xml文档转换为 Json 格式
                    string json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None);

                    var responseObject = JObject.Parse(json).GetJsonObject("response");
                    if (responseObject == null)
                    {
                        throw new Exception(responseXML);
                    }

                    if (responseObject.GetJsonObjectStringValue("flag") != "success")
                    {
                        throw ExceptionHelper.GenException("@E110000002", responseObject.GetJsonObjectStringValue("message"));
                    }
                    var receiverInfo = responseObject.GetJsonObject("receiverInfo");

                    var orderSensitiveInfo = new JObject();
                    orderSensitiveInfo["orders_no"] = orderId;
                    orderSensitiveInfo["receiver_name"] = receiverInfo.GetJsonObjectStringValue("name");
                    orderSensitiveInfo["receiver_province"] = receiverInfo.GetJsonObjectStringValue("province");
                    orderSensitiveInfo["receiver_city"] = receiverInfo.GetJsonObjectStringValue("city");
                    orderSensitiveInfo["receiver_district"] = receiverInfo.GetJsonObjectStringValue("district");
                    orderSensitiveInfo["receiver_address"] = receiverInfo.GetJsonObjectStringValue("detailAddress");
                    orderSensitiveInfo["receiver_telephone"] = receiverInfo.GetJsonObjectStringValue("tel");
                    orderSensitiveInfo["receiver_mobile"] = receiverInfo.GetJsonObjectStringValue("mobile");
                    orderSensitiveInfo["oaid"] = receiverInfo.GetJsonObjectStringValue("oaid");
                    return new JArray() { orderSensitiveInfo };
                }
                else
                {
                    //奇门云网关，即自定义奇门接口
                    DefaultQimenCloudClient client = new DefaultQimenCloudClient(url, appkey, appsecret);
                    TrinityWmsExtendQueryRequest req = new TrinityWmsExtendQueryRequest();
                    req.SetTargetAppKey(appkey);

                    JObject jParams = new JObject();
                    jParams.Add("fields", "tid,type,status,oaid,receiver_name,receiver_country,receiver_state,receiver_city,receiver_district,receiver_town,receiver_address,receiver_mobile,receiver_phone");
                    jParams.Add("tid", orderId);

                    JObject jExtend = new JObject();
                    jExtend.Add("eShopCode", eShopCode);
                    jExtend.Add("source", "api");
                    jExtend.Add("method", "taobao.trade.fullinfo.get");
                    jExtend.Add("params", jParams);

                    req.ExtendProps = jExtend.ToString();
                    TrinityWmsExtendQueryResponse rsp = client.Execute(req);

                    var responseObject = JObject.Parse(rsp.Body).GetJsonObject("response");
                    if (responseObject.GetJsonObjectStringValue("err_flag") != "success")
                    {
                        throw ExceptionHelper.GenException("@E110000002", responseObject.GetJsonObjectStringValue("err_message"));
                    }
                    var extendProps = JObject.Parse(responseObject.GetJsonObjectStringValue("extendProps"));
                    if (extendProps.GetJsonObjectValue("error_response") != null)
                    {
                        throw ExceptionHelper.GenException("@E110000002", extendProps.GetJsonObject("error_response").GetJsonObjectStringValue("sub_msg"));
                    }
                    var tradeObject = extendProps.GetJsonObject("trade_fullinfo_get_response").GetJsonObject("trade");
                    
                    var orderSensitiveInfo = new JObject();
                    orderSensitiveInfo["orders_no"] = orderId;
                    orderSensitiveInfo["receiver_name"] = tradeObject.GetJsonObjectStringValue("receiver_name");
                    orderSensitiveInfo["receiver_province"] = tradeObject.GetJsonObjectStringValue("receiver_state");
                    orderSensitiveInfo["receiver_city"] = tradeObject.GetJsonObjectStringValue("receiver_city");
                    orderSensitiveInfo["receiver_district"] = tradeObject.GetJsonObjectStringValue("receiver_district");
                    orderSensitiveInfo["receiver_address"] = tradeObject.GetJsonObjectStringValue("receiver_address");
                    orderSensitiveInfo["receiver_telephone"] = tradeObject.GetJsonObjectStringValue("receiver_phone");
                    orderSensitiveInfo["receiver_mobile"] = tradeObject.GetJsonObjectStringValue("receiver_mobile");
                    orderSensitiveInfo["oaid"] = tradeObject.GetJsonObjectStringValue("oaid");
                    return new JArray() { orderSensitiveInfo };
                }
            }
            catch (BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Info("Taobao GetOrderSensitiveInfo fail: " + ex.Message);
                throw new Exception("@E110000001");
            }
            
        }
    }
}
